package com.nebula.api.common.exception;


import cn.hutool.json.JSONUtil;
import link.ahsj.core.entitys.ApiModel;
import link.ahsj.core.entitys.CodeMsg;
import lombok.extern.log4j.Log4j2;
import org.springframework.boot.autoconfigure.web.servlet.error.AbstractErrorController;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.Objects;

/**
 * @author Eastern unbeaten
 * @email chenshiyun2011@163.com
 * @data 2019/2/20
 */
@Log4j2
@RestController
public class AppErrorController extends AbstractErrorController {

    public AppErrorController(ErrorAttributes errorAttributes) {
        super(errorAttributes);
    }

    public static final String ERROR_PATH = "/error";

    @Override
    public String getErrorPath() {
        return ERROR_PATH;
    }

    @RequestMapping(ERROR_PATH)
    public ResponseEntity error(HttpServletRequest request) {
        Map<String, Object> errorAttributes = getErrorAttributes(request, false);
        Integer status = Integer.valueOf(errorAttributes.get("status").toString());
        String message = (String) errorAttributes.get("message");
        if (HttpStatus.NOT_FOUND.value() == status) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(ApiModel.error(CodeMsg.NO_FOUND_MSG));
        }
        try {
            ApiModel apiModel = JSONUtil.toBean(message, ApiModel.class);
            if (Objects.nonNull(apiModel)) {
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                        .body(apiModel);
            }
        } catch (Exception e) {
            log.info("AppErrorController异常中的异常:" + e.getMessage());
        }
        log.error(String.format("请求地址为:%s,出错信息为:%s", errorAttributes.get("path"), message));
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(ApiModel.error(CodeMsg.SYS_ERR_MSG));
    }


}
